package pwr.zpi.twop;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.badlogic.gdx.graphics.Color;

public class ModelProvider {
	public static final int BOX_SIZE = 256;
	public static final float SCALE = 0.05f;
	
	private Color[][][] modelData;
	
	public ModelProvider(BufferedInputStream inputStream) throws IOException {
		modelData = new Color[256][256][256];
		load(inputStream);
	}

	private void load(BufferedInputStream inputStream) throws IOException {
		byte[] bytes = new byte[3];
		int bytesRead = 0;
		
		try {
			while((bytesRead = inputStream.read(bytes)) != -1) {
				if(bytesRead == 3) {
					Color color = modelData[bytes[0] + 128] [bytes[1] + 128] [bytes[2] + 128];
					color = incrementOrCreateColor(color);
					modelData[bytes[0] + 128] [bytes[1] + 128] [bytes[2] + 128] = color;
				}
				
				bytes = new byte[3];
			}
			
//			inputStream.read();
			
//			for (int i = 0; i < modelData[128].length; i++) {
//				for (int j = 0; j < modelData[128][i].length; j++) {
//					if(i%3==0 || j%2==0 || i%5==0) {
//						modelData[128][i][j] = incrementOrCreateColor(null);
//					}
//				}
//			}
			
//			modelData[128][0][1] = incrementOrCreateColor(null);
//			modelData[128][1][1] = incrementOrCreateColor(null);
//			modelData[128][2][1] = incrementOrCreateColor(null);
		} catch (IOException e) { e.printStackTrace(); }
		finally {
			if(inputStream != null) {
				inputStream.close();
			}
		}
	}
	
	public Color incrementOrCreateColor(Color color) {
		if(color == null) {
			return new Color(0, 255, 0, 0);
		} else {
			float g = color.g;
			float r = color.r;
			
			g = g > 0 ? g - 1 : g;
			r = r < 256 ? r + 1 : r;
			
			color.set(r, g, 0, 0);
			
			return color;
		}
	}

	public Color[][][] getModelData() {
		return modelData;
	}
	
	public List<DrawablePoint> getPoints() {
		List<DrawablePoint> pointList = new ArrayList<DrawablePoint>(256*256*256);
		float halfBoxSize = BOX_SIZE / 2;
		
		Color[][][] modelData = getModelData();
		for (int i = 0; i < modelData.length; i++) {
			for (int j = 0; j < modelData[i].length; j++) {
				for (int k = 0; k < modelData[i][j].length; k++) {
					if(modelData[i][j][k] != null) {
						DrawablePoint dp = new DrawablePoint();
						dp.color = modelData[i][j][k];
						dp.coords = new float[]{(i-(halfBoxSize)) * SCALE,
								(j-(halfBoxSize)) * SCALE,
								(k-(halfBoxSize)) * SCALE};
						
						pointList.add(dp);
					}
				}
			}
		}
		
		return pointList;
	}
}
